package com.wn.sms.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.wn.common.constant.redis.RedisConstant;
import com.wn.common.exception.Assert;
import com.wn.common.result.enums.impl.BusinessCode;
import com.wn.sms.config.SmsTemplate;
import com.wn.sms.service.SmsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author yellow Docter
 * @date 2023 -02-24
 * @desc
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendPhoneMessage(String phone) {
        //01 生产验证码
//        String code = RandomUtil.randomNumbers(4);
        //02 发送短信

        String lock = stringRedisTemplate.opsForValue().get(RedisConstant.SMS_LOCK + phone);

        //org.apache.commons.lang.StringUtils; 判断字符串不为null
        if (StringUtils.isNotBlank(lock)){
            if (lock.equals("lock")){
                Assert.error(BusinessCode.USER_VERIFY_LOCK);
            }
        }

//        smsTemplate.sendSms(phone,code);
        String code = "1234";
        //03 把短信验证吗存储到redis中
        stringRedisTemplate.opsForValue().set(RedisConstant.SMS_PREFIX + phone, code, 10, TimeUnit.DAYS);

        //短信轰炸 记录 、加锁
        String count = stringRedisTemplate.opsForValue().get(RedisConstant.SMS_COUNT + phone);
        if (count == null) { //第一次
            stringRedisTemplate.opsForValue().set(RedisConstant.SMS_COUNT + phone, "1", 1, TimeUnit.HOURS);
        } else {
            stringRedisTemplate.opsForValue().increment(RedisConstant.SMS_COUNT + phone);
        }
        if ("4".equals(count)) {
            stringRedisTemplate.opsForValue().set(RedisConstant.SMS_LOCK + phone, "lock", 1, TimeUnit.DAYS);
        }
    }
}
